using System.Collections.Generic;
using Framework.Timer;
using IcecreamView;
using UnityEngine;

namespace System.Game
{
    public class CameraController : ChooseController
    {

        private List<CameraNode> _gameCameras;
        private List<CameraNode> _obCameras;

        private CameraNode _curCamera;



        public void Init()
        {
            this.RefreshChoose();
            this.OnSelect = this.OnSelectCamera;
            EventManager.Instance.BindEvent(EventCode.GAME_CAMERA_NEXT,        this.CameraNext);
            EventManager.Instance.BindEvent(EventCode.GAME_CAMERA_SHAKE,       this.CameraShake);
            EventManager.Instance.BindEvent(EventCode.GAME_CAMERA_CHANEG, this.CameraChangeType);
        }

        private void OnSelectCamera(ChooseEntity obj)
        {
            this._curCamera = ((CameraNode) obj); 
        }

        private void CameraChangeType(EventArg obj)
        {
            var index = obj.GetValue<int>();
            if (index < this.ChooseDict.Count)
            {
                this.ActiveChoose(index);
            }
        }

        private void CameraShake(EventArg obj)
        {
            float inTime = obj.GetValue<float>(0);
            float time = obj.GetValue<float>(1);
            float outTime = obj.GetValue<float>(2);
            float shakeScale = obj.GetValue<float>(3);
            this._curCamera?.SetShake(inTime , time , outTime , shakeScale);
        }

        private void CameraNext(EventArg obj)
        {
            var index = this._curCamera.ChooseID + 1;
            //Debug.Log("切换相机 form：" + this._curCamera.ChooseID);
            this.ActiveChoose(index >= this._gameCameras.Count ? 0 : index);
        }

        public override void RefreshChoose()
        {
            this._gameCameras = new List<CameraNode>();
            this._obCameras   = new List<CameraNode>();
            var chooseList = new List<CameraNode>(this.GetComponentsInChildren<CameraNode>());
            this.RefreshChoose(chooseList);
            foreach (var chooseEntity in chooseList)
            {
                if (chooseEntity.CameraType == CameraType.Game)
                {
                    this._gameCameras.Add(chooseEntity);
                }
                else
                {
                    this._obCameras.Add(chooseEntity);
                }
            }
        }

        private void OnDestroy()
        {
            EventManager.Instance.UnBindEvent(EventCode.GAME_CAMERA_NEXT,        this.CameraNext);
            EventManager.Instance.UnBindEvent(EventCode.GAME_CAMERA_SHAKE,       this.CameraShake);
            EventManager.Instance.UnBindEvent(EventCode.GAME_CAMERA_CHANEG, this.CameraChangeType);
        }

    }
}